package com.fili.keygen;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * Created by IntelliJ IDEA.
 * User: fili
 * Date: Oct 2, 2006
 * Time: 9:31:25 PM
 * To change this template use File | Settings | File Templates.
 */
public class KeyEncoder
{
    public static final int encoding = 5;

    public static String encode(String name, EncodedPermission perm)
    {
        return encode(name, perm.nrUsc, perm.uscISPM, perm.uscNormal, perm.seed);
    }

    public static String encode(String name, int nrUsc, boolean uscISPM, boolean uscNormal, int seed)
    {
        String s, s1, s2;
        String enc = "ABC1DEF2GHI3JKL4MNO5PQR6STU7VXY8";

        s = name + nrUsc + uscISPM + uscNormal + seed;

        MessageDigest md5 = null;
        try
        {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(s.getBytes());
            s1 = new String(md5.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            return "ala bala";
        }

        s2 = "";
        for (int i = 0; i < 5; i++)
        {
            int v = (((int) (s1.charAt(i * 3))) << 16) + (((int) (s1.charAt(i * 3 + 1))) << 8) + (((int) (s1.charAt(i * 3 + 2))));
            for (int j = 0; j < 4; j++)
            {
                s2 += enc.charAt(v & 0x1f);
                v >>= 5;
            }
            if (i < 4)
                s2 += "-";
        }
        return s2;
    }

    public static EncodedPermission match(String name, String key)
    {
        for (int i = 0; i < (1<<encoding); i++)
            for (int j = 1; j < 9; j++)
            {
                if (key.equals(encode(name, j, true, true, i)))
                    return new EncodedPermission(j, true, true, i);
                if (key.equals(encode(name, j, true, false, i)))
                    return new EncodedPermission(j, true, false, i);
                if (key.equals(encode(name, j, false, true, i)))
                    return new EncodedPermission(j, false, true, i);
                if (key.equals(encode(name, j, false, false, i)))
                    return new EncodedPermission(j, false, false, i);
            }
        return null;
    }

    public static int getSeed()
    {
        return (new Random().nextInt()) & (1<<encoding-1);
    }
}
